package io.renren.modules.web.controller;

import io.renren.common.utils.R;
import io.renren.modules.web.entity.WebCodeEntity;
import io.renren.modules.web.service.WebCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Web代码控制器
 */
@RestController
@RequestMapping("/web/code")
public class CodeController {

    @Autowired
    private WebCodeService webCodeService;

    /**
     * 运行代码并返回结果
     */
    @PostMapping("/run")
    public R runCode(@RequestBody WebCodeEntity codeEntity) {
        String result = webCodeService.runCode(
            codeEntity.getHtmlCode(), 
            codeEntity.getCssCode(), 
            codeEntity.getJsCode()
        );
        return R.ok().put("result", result);
    }

    /**
     * 保存代码
     */
    @PostMapping("/save")
    public R saveCode(@RequestBody WebCodeEntity codeEntity) {
        boolean success = webCodeService.saveCode(codeEntity);
        if (success) {
            return R.ok("保存成功");
        } else {
            return R.error("保存失败");
        }
    }

    /**
     * 获取用户的代码列表
     */
    @GetMapping("/user/{userId}")
    public R getUserCodes(@PathVariable("userId") Integer userId) {
        List<WebCodeEntity> codes = webCodeService.getCodesByUserId(userId);
        return R.ok().put("data", codes);
    }

    /**
     * 获取公开的代码列表
     */
    @GetMapping("/public")
    public R getPublicCodes() {
        List<WebCodeEntity> codes = webCodeService.getPublicCodes();
        return R.ok().put("data", codes);
    }

    /**
     * 根据类型获取代码列表
     */
    @GetMapping("/type/{codeType}")
    public R getCodesByType(@PathVariable("codeType") Integer codeType) {
        List<WebCodeEntity> codes = webCodeService.getCodesByType(codeType);
        return R.ok().put("data", codes);
    }

    /**
     * 获取单个代码详情
     */
    @GetMapping("/{id}")
    public R getCodeById(@PathVariable("id") Integer id) {
        WebCodeEntity code = webCodeService.getById(id);
        if (code != null) {
            return R.ok().put("data", code);
        } else {
            return R.error("未找到相关代码");
        }
    }

    /**
     * 更新代码
     */
    @PutMapping("/update")
    public R updateCode(@RequestBody WebCodeEntity codeEntity) {
        boolean success = webCodeService.updateById(codeEntity);
        if (success) {
            return R.ok("更新成功");
        } else {
            return R.error("更新失败");
        }
    }

    /**
     * 删除代码
     */
    @DeleteMapping("/{id}")
    public R deleteCode(@PathVariable("id") Integer id) {
        boolean success = webCodeService.removeById(id);
        if (success) {
            return R.ok("删除成功");
        } else {
            return R.error("删除失败");
        }
    }
} 